﻿MyApp.module("NewEntryModule", function (NewEntryModule, MyApp, Backbone, Marionette, $, _) {


    NewEntryModule.main = null;
    NewEntryModule.startWithParent = false;
    NewEntryModule.view = null;
    NewEntryModule.view_categories = null;
    NewEntryModule.categories = null;
    NewEntryModule.daily = null;

    NewEntryModule.addInitializer(function(){

    });

    NewEntryModule.addFinalizer(function () {
        NewEntryModule.main.close();
        NewEntryModule.main = null;
        NewEntryModule.view = null;
    });


    //Functions
    MyApp.module("NewEntryModule").on('start', function (region) {

        console.log("NewEntryModule:on:start start...");
        //Load Daily
        NewEntryModule.daily = new Daily();
        NewEntryModule.daily.fetch({
            data: {
                when: "today"
            }
        });
        NewEntryModule.view = new NewEntry_ModuleView();
        //Load Categories
        var entries = new Entries();
        console.log("NewEntryModule:on:start Loading Categories for User: " + MyApp.user.get('email') + " ID: " + MyApp.user.get('id'));
        entries.fetch({
            data: {
                sessionId: MyApp.user.get('sessionId'),
                when: "today"
            }
        });

        this.view_categories = new NewEntry_CategoriesView({
            collection: entries
        });

        this.categories = entries;

        //Open Views
        NewEntryModule.main = region;
        NewEntryModule.main.show(this.view);
        NewEntryModule.view.categories.show(this.view_categories);
        console.log("NewEntryModule:on:start stop.");
    });

    MyApp.module("NewEntryModule").on('CategoriesView:save', function(){
        var myModel;
        console.log("NewEntryModule:on:CategoriesView:save start...");

        for(var i=0; i<this.categories.length;i++){
            myModel = this.categories.models[i];
            myModel.save({},{url: webserviceUrl + entriesUrl + '?sessionId=' + MyApp.user.get("sessionId")});
        };
        NewEntryModule.daily.save({},{url: webserviceUrl + dailyUrl + '?sessionId=' + MyApp.user.get("sessionId")});
        console.log("NewEntryModule:on:CategoriesView:save stop");
    });


});